﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using IServices;
using LinqRepositories;
using Services.Validation;
using IRepositories;
using GestionLinqLibData;



namespace Services
{
    public class MatiereService : IMatiereService
    {
        private IValidationDictionary _validationDictionary;
        private IMatiereRepository _repository;

        public MatiereService(IValidationDictionary validationDictionary)
            : this(validationDictionary, new LinqMatiereRepository())
        { }

        public MatiereService(IValidationDictionary validationDictionary, IMatiereRepository repository)
        {
            _validationDictionary = validationDictionary;
            _repository = repository;


        }

        protected bool ValidateMatiere(matiere matiereToValidate)
        {
            if (matiereToValidate.nom_matiere.Trim().Length == 0)
            {
                _validationDictionary.AddError("nom_matiere", "nom null");
            }

            return _validationDictionary.IsValid;
        }



        #region IMatiereService Membres

        public bool CreateMatiere(matiere matiereToCreate)
        {
            if (!ValidateMatiere(matiereToCreate))
                return false;

            try
            {
                _repository.CreateMatiere(matiereToCreate);
            }
            catch
            {

                return false;
            }
            return true;
        }

        public IEnumerable<matiere> ListMatieres()
        {
            return _repository.ListMatieres();
        }

        public matiere GetMatiere(int id_mat)
        {
            return _repository.GetMatiere(id_mat);
        }

        public bool EditMatiere(matiere matiereToEdit)
        {
            if (!ValidateMatiere(matiereToEdit))
                return false;

            try
            {
                _repository.EditMatiere(matiereToEdit);
            }
            catch(Exception e)
            {

                _validationDictionary.AddError("Erreur", "Erreur :"+e.Message);
                return false;
            }

            return true;
        }

        public bool DeleteMatiere(matiere matiereToDelete)
        {
            try
            {
                _repository.DeleteMatiere(matiereToDelete);
            }
            catch
            {

                return false;
            }

            return true;
        }

        #endregion
    }
}
